package com.bitcat.firstapp.demo.servicedemo

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityServiceDemoBinding
import es.dmoral.toasty.Toasty

class ServiceDemoActivity : AppCompatActivity() {

    private val binding:ActivityServiceDemoBinding by lazy {
        ActivityServiceDemoBinding.inflate(layoutInflater)
    }
    private var  myService:MyService? = null

    private val conn = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
           //服务连接成功
            val binder = service as MyService.MyBinder
            myService = binder.getService()
            Toasty.success(this@ServiceDemoActivity,"服务连接成功").show()
        }

        //
        override fun onServiceDisconnected(name: ComponentName?) {
            //服务断开连接
            myService = null
            Toasty.success(this@ServiceDemoActivity,"服务断开连接").show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(30, 200, 30, systemBars.bottom)
            insets
        }

        setClickListeners()
    }

    private fun setClickListeners() {
        binding.btnStartService.setOnClickListener {
            startService(Intent(this,MyService::class.java))
        }

        binding.btnStopService.setOnClickListener {
            stopService(Intent(this,MyService::class.java))
        }

        binding.btnBindService.setOnClickListener {
            val intent = Intent(this,MyService::class.java)
            bindService(intent,conn,BIND_AUTO_CREATE)
        }

        binding.btnUnbindService.setOnClickListener {
            if (myService != null){
                unbindService(conn)
                myService = null
            }

        }

        binding.btnGetServiceData.setOnClickListener {
            if (myService != null){
                binding.tvServiceData.text = myService!!.getCount().toString()
            }else{
                Toasty.error(this,"请先绑定服务").show()
            }
        }


    }

    override fun onDestroy() {
        if (myService != null){
            unbindService(conn)
        }
        super.onDestroy()
    }
}